package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;
    /*pagehelper分页查询*/
    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
        //设置分页查询参数
        PageHelper.startPage(empQueryParam.getPage(),empQueryParam.getPageSize());
        //执行查询
        List<Emp> empList = empMapper.list(empQueryParam);
        Page<Emp> p= (Page<Emp>) empList;
        return new PageResult<>(p.getTotal(),p.getResult());
    }
    @Transactional//事务管理
    @Override
    public void save(Emp emp) {
        try {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            //基本信息
            empMapper.insert(emp);
            //工作经历
            List<EmpExpr> exprList = emp.getExprList();

            if(!CollectionUtils.isEmpty(exprList)){
                //遍历集合为empId赋值
                exprList.forEach(empExpr -> {
                    empExpr.setEmpId(emp.getId());
                });
                empExprMapper.insertBatch(exprList);
            }
        } finally {
                //记录操作日志
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), "新增员工：" + emp);
            empLogService.insertLog(empLog);
        }

    }
    @Transactional(rollbackFor = {Exception.class})//开启事务控制
    @Override
    public void delete(List<Integer> ids) {

        //删除员工的基本信息
        empMapper.deleteByIds(ids);
        //删除员工的工作经历
        empExprMapper.deleteByEmpIds(ids);
    }

    @Override
    public Emp getInfo(Integer id) {

        return empMapper.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Emp emp) {

        //根据ID修改员工的基本信息
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.updateById(emp);
        //根据ID修改员工的工作经历
        //先删除 后添加
        empExprMapper.deleteByEmpIds(Arrays.asList(emp.getId()));

        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            empExprMapper.insertBatch(exprList);
        }

    }

    @Override
    public List<Emp> findAll() {
        return  empMapper.findAll();
    }

    @Override
    public LoginInfo login(Emp emp) {
        Emp e=empMapper.selectByUsernameAndPassword(emp);

        Map<String,Object> claims=new HashMap<>();
        claims.put("id", emp.getId());
        claims.put("username", emp.getUsername());
        /*生成JWT令牌*/
        String jwt = JwtUtils.generateToken(claims);
        if(e!=null){
            log.info("登录成功，员工信息：{}",e);
            return new LoginInfo(e.getId(),e.getUsername(),e.getName(),jwt);
        }
        return null;
    }
    /*原始分页查询*/
    /*
    @Override
    public PageResult<Emp> page(Integer page, Integer pageSize) {
        long total = empMapper.count();
        Integer start=(page-1)*pageSize;
        List<Emp> rows = empMapper.list(start, pageSize);
        return new PageResult<Emp>(total,rows);
    }*/
}
